﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Text;
using Microsoft.SharePoint;

namespace SIMSProject.Views.Inventory.ImportData
{
    public partial class ImportDataUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.LoadData();
            }
        }

        private void LoadData()
        {
            ListItemCollection items = new ListItemCollection();
            items.Add(new ListItem("Material", "Material"));
            items.Add(new ListItem("Product", "Product"));

            this.ddlImportType.DataSource = items;
            this.ddlImportType.DataBind();
        }

        private DataTable GetDataTableFromCSVFile()
        {
            DataTable table = new DataTable();
            int totalError = 0;
            double numeric = new double();

            string data = Encoding.Default.GetString(this.fuImport.FileBytes);
            string[] csvData = data.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            if (csvData.Length <= 0)
            {
                return table;
            }

            string[] header = csvData[0].Split(new string[] { "," }, StringSplitOptions.None);

            for (int i = 0; i < header.Length; i++)
            {
                table.Columns.Add(header[i], typeof(string));
            }

            for (int i = 1; i < csvData.Length; i++)
            {
                if (!string.IsNullOrEmpty(csvData[i].Replace(",", string.Empty)))
                {
                    string[] values = this.TranslateString(csvData[i]).Split(new string[] { "," }, StringSplitOptions.None);

                    if (values.Length >= 25)
                    {
                        DataRow row = table.NewRow();
                        for (int j = 0; j < table.Columns.Count; j++)
                        {
                            if (j == 2 || j == 11 || j == 13 || j == 19 || j == 20)
                            {
                                if (!Double.TryParse(values[j].Replace('.', ','), out numeric))
                                {
                                    numeric = -1;
                                }

                                if (values[j].Contains(","))
                                {
                                    row[j] = numeric.ToString("N");
                                }
                                else
                                {
                                    row[j] = numeric.ToString();
                                }
                            }
                            else
                            {
                                row[j] = values[j];
                            }
                        }

                        table.Rows.Add(row);
                    }
                    else
                    {
                        totalError++;
                        //string error = this.textboxResult.Text;
                        //error += "\nError 9: Subscript out of range en linea " + i.ToString() + " del archivo";
                    }
                }
                else
                {
                    totalError++;
                    //string error = this.textboxResult.Text;
                    //error += "\nError 9: Subscript out of range en linea " + i.ToString() + " del archivo";
                }
            }

            //this.totalError.Text = totalError.ToString();
            //this.totalRecord.Text = Convert.ToString(csvData.Length - 1);
            return table;
        }

        private string TranslateString(string value)
        {
            string returnValue = string.Empty;
            bool inString = false;
            for (int i = 0; i < value.Length; i++)
            {
                if (value[i] == '"' && !inString)
                {
                    inString = true;
                }
                else if (value[i] == '"' && inString)
                {
                    inString = false;
                }

                if (value[i] != '"')
                {
                    if (value[i] == ',' && inString)
                    {
                        returnValue = returnValue + ';';
                    }
                    else
                    {
                        returnValue = returnValue + value[i];
                    }
                }
            }

            return returnValue;
        }

        protected void btImport_Click(object sender, EventArgs e)
        {
            string type = this.ddlImportType.SelectedValue;
            
            SPList list = SPContext.Current.Web.Lists[type];

            for (int i = list.ItemCount - 1; i >= 0; i--)
            {
                list.Items.Delete(i);
                list.Update();
            }

            string data = Encoding.Default.GetString(this.fuImport.FileBytes);
            string[] csvData = data.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            if (csvData.Length <= 0)
            {
                return;
            }

            for (int i = 1; i < csvData.Length; i++)
            {
                if (!string.IsNullOrEmpty(csvData[i].Replace(",", string.Empty)))
                {
                    string[] values = this.TranslateString(csvData[i]).Split(new string[] { "," }, StringSplitOptions.None);
                    int quantity = 0;
                    int price = 0;

                    Int32.TryParse(values[3], out quantity);
                    Int32.TryParse(values[4], out price);

                    SPListItem item = list.AddItem();
                    item["Title"] = values[0];
                    item[type+" Code"] = values[1];
                    item["Description"] = values[2];
                    item["Quantity"] = quantity;
                    item["Price"] = price;

                    if (string.Equals(type, "Material"))
                    {
                        item["Category"] = values[5];
                        item["Type of unit"] = values[6];
                        item["Position"] = values[7];
                    }
                    else
                    {
                        item["Type of unit"] = values[5];
                        item["Position"] = values[6];
                    }
                    item.Update();
                }
            }
        }
    }
}
